var places=[];
var places_markers=[];
var targetPolygons=[]; //google map objects
var neighborPolygons=[]; //google map objects
var targetCoordinates=[];  //json coordinates, 2-dimention array, place|coordinate
var neighborCoordinates=[];  //json coordinates, 2-dimention array, place|coordinate

KSR.Search={
	init:function(){
		var self=this;
		var mapTopPosition = $('#map-top').offset();
		if (typeof mapTopPosition !== "undefined"){
//			console.log("mapTopPosition="+mapTopPosition.top);
//			console.log("left-rail bottom:"+($('#left-rail-bottom').offset().top));
			$(window).on("scroll",function(){
//				console.log("pageYOffset+mapHeight:"+(pageYOffset+$('#map-top').height()));
//				console.log("$('.main-column .left-rail').height():"+$('.main-column .left-rail').height());
				if(pageYOffset > mapTopPosition.top &&  $('#map-top').height()<$('.main-column .left-rail').height()){
					if ((pageYOffset+$('#map-top').height())>$('#left-rail-bottom').offset().top){
						$("#map-top").removeClass("fixed-position");
						$("#map-top").addClass("abs-position");
					} else {
						$("#map-top").removeClass("abs-position");
						$("#map-top").addClass("fixed-position");
					}
				} else {
					$("#map-top").removeClass("fixed-position");
					$("#map-top").removeClass("abs-position");
				}
			});
		}
	},
	onMapLoadCallback:function(map){
		var self = this;
        google.maps.event.addListener(mapUtil.mapInstance, "dragstart", function(){
	        //todo block ui
        });		
        google.maps.event.addListener(mapUtil.mapInstance, "dragend", function(){
			//check if redo search box is checked, do search and update markers	
//        	KSR.Search.ajaxCallForData();
        });	
        if (places!=null&&places.length>0){
        	KSR.Search.addMarkers(places,places_markers,true);
        }
        if (typeof neighborCoordinates !== "undefined"&&neighborCoordinates!==null){
        	var plg;
        	for ( var key in neighborCoordinates) {
//        		console.log("key="+key);
        		neighborPolygons[key]=mapUtil.drawPolygon(key,neighborCoordinates[key],"neighbor",function(key){
//        			console.log("====click on "+key);
        			//click on the map polygon to trigger the filter search
        			$(".location-filters.checkbox input[type='checkbox'][label='"+key+"']").trigger("click");
    			});
        	}
        	mapUtil.resetViewport();
        }
        if (typeof targetCoordinates !== "undefined"&&targetCoordinates!==null){
        	var plg;
        	for ( var key in targetCoordinates) {
//        		console.log("key="+key);
				targetPolygons[key]=mapUtil.drawPolygon(key,targetCoordinates[key],"target");
			}
        	mapUtil.resetViewport();
        }
        $(".ksr .filters .checkbox label").each(function(){
        	//		console.log("label.text()="+$(this).text());
        	var self=this;
        	if (typeof targetPolygons[$(self).text().trim()]!=="undefined"){
        		$(self).parents(".checkbox").hover(function(){
        			try{
        				google.maps.event.trigger(targetPolygons[$(self).text().trim()],"mouseover");
        			} catch(e){}
        		},function(){
        			try{
        				google.maps.event.trigger(targetPolygons[$(self).text().trim()],"mouseout");
        			} catch(e){}
        		})
        	}
        	if (typeof neighborPolygons[$(self).text().trim()]!=="undefined"){
        		$(self).parents(".checkbox").hover(function(){
        			try{
        				google.maps.event.trigger(neighborPolygons[$(self).text().trim()],"mouseover");
        			} catch(e){}
        		},function(){
        			try{
        				google.maps.event.trigger(neighborPolygons[$(self).text().trim()],"mouseout");
        			} catch(e){}
        		})
        	}
        })
	},
	addMarkers:function(places,markers,isResetViewport){
		for (var i=0;i<places.length;i++){
			places[i].markerImage=mapUtil.getNumberMarkerImage(places[i].number);
			places[i].hoverImage=mapUtil.getNumberMarkerHoverImage(places[i].number);
			//places[i].mouseOverLabelHtml="<div id=\"marker\"><nobr>" + places[i].name + "</nobr></div>";
			places[i].infoWindowHtml= KSR.Search.createInfoWindow(places[i],".search-listing div[office-id="+places[i].id+"] .for-infowindow");
			places[i].infoWindowPixlOffset_x = -110;
			places[i].infoWindowPixlOffset_y = -45;		
			markers.push(mapUtil.addMarker(mapUtil.mapInstance,places[i]));
		}
		if (isResetViewport!=null&&isResetViewport)
			mapUtil.resetViewport();	
		
		//mouse over the item area highlights the marker
		$(".ksr .search-result .search-item").each(function(idx){
			var that=this;
    		$(that).hover(function(){
    			try{
    				google.maps.event.trigger(markers[idx],"mouseover");
    			} catch(e){}
    		},function(){
    			try{
    				google.maps.event.trigger(markers[idx],"mouseout");
    			} catch(e){}
    		});
		});
	},
	createInfoWindow:function(place,contentCssSelector){
		var html="<div id=\""+place.id+"\" class=\"module info-window-box position-rel font-14\" style=\"background-color:white;\">";
			//retrieve the html from dom
			html+=$(contentCssSelector).html();
			html += "<div class=\"close-button position-abs\" onClick=\"javascript:mapUtil.closeInfoWindow()\"><i class=\"icon-remove-sign icon-2x css-pie\"></i></div>";
			html += "<div class=\"bubble-arrow border\"></div>";
			html += "<div class=\"bubble-arrow\"></div>";
			html += "</div>";				
			html += "</div>";
		return html;
	},
	getBasicInfoHtml:function(place){
		var html="";
		html += "<div class=\"font-14 margin-bottom-half\">"+place.number+". ";
		html += "<a class=\"title font-14\" href=\""+place.profileUrl+"\">" + place.name+"</a>";
		html += "</div>";	
		
		html+="<div class=\"margin-top-half rating font-orange font-14\">";
		for ( var int = 0; int < 5; int++) {
			if ((place.avgRating-int-1)>=0.0)
				html += "<i class=\"icon-star\" style=\"margin-right:2px\"></i>";
			else if ((place.avgRating-int-1)<0.0&&(place.avgRating-int-1)>=-0.5)
				html += "<i class=\"icon-star-half-empty\" style=\"margin-right:2px\"></i>";
			else
				html += "<i class=\"icon-star-empty\" style=\"margin-right:2px\"></i>";
		}
		
		html += "<span class=\"review-count margin-left-half font-dark font-13\">";
		if ((place.reviewCount>1))
			html += place.reviewCount+" reviews";
		else
			html += place.reviewCount+" review";
		html += "</span>";
		html += "</div>";

		if (place.specialty != ""){
			html += "<div class=\"margin-top-half \">";
			html += "<span class=\"font-14\">Specialty:</span>";
			html += "<span class=\"font-14\">";
			html += place.specialty;
			html += "</span>";
			html += "</div>";
		}
		if (place.price != ""){
			html += "<div class=\"margin-top-half \">";
			html += "<span class=\"font-14\">Price:</span>";
			html += "<span class=\"font-14\"> $";
			html += place.price;
			html += "/hr</span>";
			html += "</div>";
		}
			
		html += "  <div class=\"font-14 margin-vertical-half\"><span class=\"icon  margin-right\"><i class=\"icon-location-arrow font-dark icon-large\"></i></span>" + place.address + ", " + place.city + ", " + place.state + " " + place.zip+"</div>";
		if (place.phoneNumber != ""){
			html += " <div class=\"font-14 margin-bottom-half\"><span class=\"margin-right-half\"><i class=\"icon-phone icon-large\"></i></span> " + place.phoneNumber + "</div>";
		}
		
		return html;
	},
	createOfficeListHtml:function(offices){
		var html="";
		for ( var i = 0; i < offices.length; i++) {
			html+="<div class=\"search-item full-width\" office-id=\""+offices[i]+"\">";
			html+=KSR.Search.getBasicInfoHtml(offices[i]);
			if (offices[i].emailAddress != ""){
				html += "<div class=\"margin-top-half \">";
				html += "<span class=\"font-14\">Email:</span>";
				html += "<span>";
				html += "<a class=\"font-14\" href=\"mailto:"+offices[i].emailAddress+"\">";
				html += offices[i].emailAddress;
				html += "</a>";
				html += "</span>";
				html += "</div>";
			}		
			html+="<div class=\"margin-top-half\">";
			html+="	<span class=\"icon  margin-right\"><i class=\"icon-map-marker icon-large\"></i></span>";
			html+="	<span class=\"get-direction\">";
			html+="		<a href=\"#\">Get Direction</a>";
			html+="	</span>";
			html+="</div>";

			html+="<div class=\"margin-top-half\">";
			html+="	<label>Owned by:</label>";
			html+="	<span class=\"business-name\">";
			html+="		<a href=\""+offices[i].businessUrl+"\">"+offices[i].businessName+"</a>";
			html+="	</span>";
			html+="</div>";
			
			html+="<div class=\"margin-top-half\">";
			html+="	<p class=\"serif font-dark font-15\">";
			html+=  offices[i].description;
			html+="	</p>";
			html+="</div>";
			html+="</div>";
			//if not last, add separate row
			if (i<offices.length-1){
				html+="<div class=\"separate-row-single-1px\"></div>";
			}
			
		}
		return html;
	},
	ajaxCallForData:function(){
		var center_lat=mapUtil.mapInstance.getCenter().lat();
		var center_lon=mapUtil.mapInstance.getCenter().lng();
			
        var  url ="/ksr/search.json"+"?latitude="+center_lat+"&longitude="+center_lon;
           $.getJSON(url, function(offices) {
                if (offices!=null && offices.length>0){
//					console.log("offices:"+offices)
                	$("#officeListWrapper").html(KSR.Search.createOfficeListHtml(offices));
            		for (var i=0;i<places_markers.length;i++){
            			places_markers[i].setMap(null);
            		}
            		places_markers=[];
            		KSR.Search.addMarkers(offices,places_markers,false)
                }
            });		
	}
	
}

$(document).ready(function(){
	KSR.Search.init();
})